"""
健康检查API端点
"""
from datetime import datetime
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import text
from app.db.session import get_db
from app.config import settings
import redis

router = APIRouter()


@router.get("/")
async def health_check():
    """基础健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "service": "智能视频内容结构重构平台",
        "version": "1.0.0"
    }


@router.get("/detailed")
async def detailed_health_check(db: Session = Depends(get_db)):
    """详细健康检查"""
    health_status = {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "service": "智能视频内容结构重构平台",
        "version": "1.0.0",
        "components": {}
    }

    # 检查数据库连接
    try:
        db.execute(text("SELECT 1"))
        health_status["components"]["database"] = {
            "status": "healthy",
            "message": "数据库连接正常"
        }
    except Exception as e:
        health_status["components"]["database"] = {
            "status": "unhealthy",
            "message": f"数据库连接失败: {str(e)}"
        }
        health_status["status"] = "unhealthy"

    # 检查Redis连接
    try:
        r = redis.Redis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            password=settings.REDIS_PASSWORD,
            decode_responses=True
        )
        r.ping()
        health_status["components"]["redis"] = {
            "status": "healthy",
            "message": "Redis连接正常"
        }
    except Exception as e:
        health_status["components"]["redis"] = {
            "status": "unhealthy",
            "message": f"Redis连接失败: {str(e)}"
        }
        health_status["status"] = "unhealthy"

    # 检查S3存储
    try:
        from app.core.storage.storage_manager import StorageManager
        storage = StorageManager()
        # 尝试列出bucket中的文件
        storage.s3_client.list_objects_v2(Bucket=storage.bucket_name, MaxKeys=1)
        health_status["components"]["storage"] = {
            "status": "healthy",
            "message": "对象存储连接正常"
        }
    except Exception as e:
        health_status["components"]["storage"] = {
            "status": "unhealthy",
            "message": f"对象存储连接失败: {str(e)}"
        }
        health_status["status"] = "unhealthy"

    # 检查配置
    try:
        required_configs = [
            "OPENAI_API_KEY",
            "S3_ENDPOINT",
            "S3_ACCESS_KEY",
            "S3_SECRET_KEY"
        ]

        missing_configs = []
        for config in required_configs:
            if not getattr(settings, config, None):
                missing_configs.append(config)

        if missing_configs:
            health_status["components"]["configuration"] = {
                "status": "warning",
                "message": f"缺少配置项: {', '.join(missing_configs)}"
            }
        else:
            health_status["components"]["configuration"] = {
                "status": "healthy",
                "message": "配置项完整"
            }
    except Exception as e:
        health_status["components"]["configuration"] = {
            "status": "unhealthy",
            "message": f"配置检查失败: {str(e)}"
        }
        health_status["status"] = "unhealthy"

    return health_status